package org.bbs.demo.reply.api;


import org.bbs.demo.advice.BusinessException;
import org.bbs.demo.common.BBSConstants;
import org.bbs.demo.common.Result;
import org.bbs.demo.reply.dao.StoreyReplyDao;
import org.bbs.demo.reply.dto.StoreyReplyDto;
import org.bbs.demo.utils.jwtutil.JWTutil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

@RestController
@RequestMapping("/comment")
@Transactional //事务声明，表示该类的所有方法都是事务性的，即方法中的所有访问数据库操作构成了一个整体事务，具有原子性
public class StoreyReplyAPI {
    @Autowired
    private StoreyReplyDao storeyreplydao;

    @PostMapping("/storeyReply/add")
    public Result info(@RequestBody StoreyReplyDto storeyreplydto,@RequestHeader String Token){
        try{

            String userId = JWTutil.getUserID(Token);
            String storeyrid = UUID.randomUUID().toString().replace("-","");
            storeyreplydto.setUser_id(userId);
            storeyreplydto.setStorey_r_id(storeyrid);
            //storeyreplydto.setBBS_user_id(storeyreplydao.findUidFromRid(storeyreplydto.getR_id()));
            if(storeyreplydao.findUser(storeyreplydto.getUser_id()) == null ||
                    storeyreplydao.findUser(storeyreplydto.getBBS_user_id()) == null){
                throw new BusinessException("用户id不存在");
                //return Result.err(BBSConstants.CODE_ERR_BUSINESS,"用户的id不存在");
            }
            if(storeyreplydao.findReply(storeyreplydto.getR_id()) == null){
                throw new BusinessException("回复评论的id不存在");
                //return Result.err(BBSConstants.CODE_ERR_BUSINESS,"回复评论的id不存在");
            }
            storeyreplydao.addStoreyReply(storeyreplydto);
            storeyreplydao.updateRReplyNum(storeyreplydto.getR_id());
            return Result.OK("回复成功",storeyreplydto);

        }catch (DuplicateKeyException err) {
            throw new BusinessException("回复失败");
            //return Result.err(BBSConstants.CODE_ERR_SYS, "回复失败");
        }
    }
}
